import logging
import os

import uvicorn
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException

# 导入 fastApi 子模块
from routers import chat_router
from routers import chat_session_router
from routers import document_router
from routers.base import failure

# FastAPI 主入口
app = FastAPI()

# 将 fastApi 子模块整合到 app 中
app.include_router(chat_router.router)
app.include_router(chat_session_router.router)
app.include_router(document_router.router)


@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request, exc):
    """
    重写 fastApi 错误信息
    """
    return JSONResponse(
        failure(exc.status_code, exc.detail), status_code=exc.status_code
    )



def run_server():
    host = os.getenv("HOST", "0.0.0.0")
    port = int(os.getenv("PORT", "8082"))
    log_level = os.getenv("LOG_LEVEL", "debug")
    reload = os.getenv("ENV") == "development"

    try:
        uvicorn.run(
            app,
            host=host,
            port=port,
            log_level=log_level,
            reload=reload,
            access_log=True,    # 是否记录访问日志

        )
    except Exception as e:
        print(f"Failed to start server: {e}")
        # 可替换为 logging.error 或集成进监控系统
# 设置日志格式
logging.basicConfig(
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    level=logging.DEBUG
)

if __name__ == "__main__":
    run_server()

